package com.example.receivesms;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.TextView;

public class ReceiveSMSActivity extends Activity {
	public static int transactionId = 0;
	static TextView messageBox;
	public static ArrayList<TransactionProcessing> transactionLst;
	public static DatabaseHandler db;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		transactionLst = new ArrayList<TransactionProcessing>();
		messageBox = (TextView) findViewById(R.id.messageBox);
		// test();
		Log.e("Insert: ", "Inserting ..");
		db = new DatabaseHandler(this);
		//db.deleteAllContact();
//		db.addContact(new Contact("Truong Tu Hai", "0979316733", "HHD001", "35000000"));
//		db.addContact(new Contact("Tran Trung Hieu", "0973807124", "HHD002", "76650000"));
//		db.addContact(new Contact("Phan Nang Duy", "0972071089", "HHD003", "22050000"));
//		db.addContact(new Contact("Test 1", "15555215556", "HHD004", "26050000"));
//		db.addContact(new Contact("Test 2", "15555215554", "HHD005", "66050000"));
//		List<Contact> contacts = db.getAllContacts();
//		for (Contact cn : contacts) {
//			Log.e("Contact", cn._phone);			
//		}
	}


	public static void updateMessageBox(String msg) {
		messageBox.append(msg);

	}

	

	public static void processSMS(SmsMessage mess,SmsManager smsManager) {
		String msg = mess.getDisplayMessageBody();
		String splitStr[] = msg.split("\\ ");
		if (splitStr[0].compareTo("BAB") == 0) {
			if (splitStr[1].compareTo("CK") == 0) {
				if (!msg.endsWith("XNCT")) {
					// 1)Kiem tra tai khoan dich
					// 2)Kiem tra so du trong tai khoan
					double amount = Double.parseDouble(splitStr[3]);
					double balac = Double.parseDouble(getBalanceByPhone(mess.getOriginatingAddress(), db));
					if (amount < balac) {
						// 3)Lay ra tai khoan nguon
						String source = getAccNumberByPhone(mess.getOriginatingAddress(), db);
						// 4)Hop le
						transactionId++;
						TransactionProcessing transaction = new TransactionProcessing(transactionId,
								source, splitStr[2], amount);
						transactionLst.add(transaction);
						// 5)Gui lai so tai khoan nhan de review
						String desName = getAccNameByAccNumber(splitStr[2], db);
						String messageConfirm = "Ban co muon chuyen " + splitStr[3] + " cho " + desName + " co so TK la " + splitStr[2] + "? " + transactionId;
						smsManager.sendTextMessage(mess.getOriginatingAddress(), null, messageConfirm, null, null);
					}
					else {
						smsManager.sendTextMessage(mess.getOriginatingAddress(), null, "Tai khoan quy khach khong du", null, null);
					}
				} else { // Gui lai transaction Id va cac thong tin
					// VD BAB CK TRANSID
					int transactionId = Integer.parseInt(splitStr[2]);
					TransactionProcessing trans = null;
					for (int i = 0; i < transactionLst.size(); i++) {
						trans = transactionLst.get(i);
						if (trans.getId() == transactionId) {
							transactionProcessing(trans);
							transactionLst.remove(i);
							break;
						}
					}
					smsManager.sendTextMessage(mess.getOriginatingAddress(), null, "Chuyen tien thanh cong", null, null);
				}
			}
			else if (splitStr[1].compareTo("SD") == 0) {
				String resBalac = getBalance(mess.getDisplayOriginatingAddress());
				smsManager.sendTextMessage(mess.getOriginatingAddress(), null, resBalac, null, null);
				Log.e("TAG","da gui mess");
			} else if (splitStr[1].compareTo("GD") == 0) {

			} else if (splitStr[1].compareTo("DT") == 0) {
				String t=getBalanceByPhone(mess.getOriginatingAddress(), db);
				Log.e("TAG",t);
				double balance=Double.parseDouble(getBalanceByPhone(mess.getOriginatingAddress(), db));
				double amount=Double.parseDouble(splitStr[2]);
				if (balance>amount) {
					balance=balance-amount;
					setBalanceByAccNumber(mess.getOriginatingAddress(), balance, db);
					
					// Ghi lai lich su giao dich
					Calendar cal = Calendar.getInstance();
					Transaction newTrans = new Transaction(mess.getOriginatingAddress(), "Nap the DT", "" + amount, cal.getTime().toString());
					db.addTransaction(newTrans);
					smsManager.sendTextMessage(mess.getOriginatingAddress(), null, "So the cua ban la 951456327896", null, null);
				} else {
					smsManager.sendTextMessage(mess.getOriginatingAddress(), null, "Khong du tien trong TK", null, null);
				}
			}
		}
	}
	
	public static String getBalance(String phoneNo) {
		String result = "Tai khoan ";
		result += getAccNumberByPhone(phoneNo, db);
		result += " co so du la " + getBalanceByPhone(phoneNo, db) + "VND";
		return result;
	}
	
	public static String getBalanceByPhone(String phoneNo, DatabaseHandler db) {
		String result = "";
		List<Contact> contacts = db.getAllContacts();
		for (Contact cn : contacts) {
			if (cn._phone.compareTo(phoneNo)==0) {
				
				
				//f.format(cn._balance);
				Log.e("TAG", cn._balance);
				result += cn._balance;
				break;
			}
		}
		return result;
	}
	
	public static String getBalanceByAccNumber(String accNo, DatabaseHandler db) {
		String result = "";
		List<Contact> contacts = db.getAllContacts();
		for (Contact cn : contacts) {
			if (cn._acc_number.compareTo(accNo)==0) {
				result += cn._balance;
				break;
			}
		}
		return result;
	}
	
	public static void setBalanceByAccNumber(String accNo, double balance, DatabaseHandler db) {
		Contact contact = getContactByAccNumber(accNo, db);
		contact.setBalance("" + balance);
		db.updateContact(contact);
	}
	
	public static Contact getContactByAccNumber(String accNo, DatabaseHandler db) {
		return db.getContact(accNo);
	}
	
	public static String getAccNumberByPhone(String phoneNo, DatabaseHandler db) {
		String result = "";
		List<Contact> contacts = db.getAllContacts();
		//Log.e("TAG", phoneNo);
		for (Contact cn : contacts) {
			//Log.e("Contact", cn._phone);
			if (cn._phone.compareTo(phoneNo)==0) {
				result += cn._acc_number;
				break;
			}
		}
		return result;
	}
	
	
	public static String getAccNameByAccNumber(String accNo, DatabaseHandler db) {
		String result = "";
		List<Contact> contacts = db.getAllContacts();
		for (Contact cn : contacts) {
			//Log.e("Contact", cn._phone);
			if (cn._acc_number.compareTo(accNo)==0) {
				result += cn._name;
				break;
			}
		}
		return result;
	}
	
	public static void transactionProcessing(TransactionProcessing tranp) {
		double desBalac = Double.parseDouble(getBalanceByAccNumber(tranp.getDestination(), db));
		double srcBalac = Double.parseDouble(getBalanceByAccNumber(tranp.getSource(), db));
		desBalac += tranp.getAmount();
		srcBalac -= tranp.getAmount();
		setBalanceByAccNumber(tranp.getDestination(), desBalac, db);
		setBalanceByAccNumber(tranp.getSource(), srcBalac, db);
		// Ghi lai lich su giao dich
		Calendar cal = Calendar.getInstance();
		Transaction newTrans = new Transaction(tranp.getSource(), tranp.getDestination(), "" + tranp.getAmount(), cal.getTime().toString());
		db.addTransaction(newTrans);
	}
}

